package com.github.binarywang.demo.wechat.service;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.binarywang.demo.wechat.entity.User;
import com.github.binarywang.demo.wechat.entity.WxUserDetail;
import com.github.binarywang.demo.wechat.repository.UserRepository;
import com.github.binarywang.demo.wechat.repository.WxUserRepository;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private WxUserRepository wxUserRepository;

	@Override
	public User queryByUserName(String username) {
		User user = null;
		List<User> list = userRepository.findAll((root, query, cb) -> {
			return cb.equal(root.get("username"), username);
		});
		if (!list.isEmpty()) {
			user = list.get(0);
		}
		return user;
	}

	@Override
	public User queryByWXUserId(String wxUserId) {
		User user = null;
		List<User> list = userRepository.findAll((root, query, cb) -> {
			return cb.equal(root.get("wxUserId"), wxUserId);
		});
		if (!list.isEmpty()) {
			user = list.get(0);
		}
		return user;
	}

	@Transactional
	@Override
	public User queryAndBindByMobile(WxUserDetail wxUser, String userId) {
		User user = null;
		List<User> list = userRepository.findAll((root, query, cb) -> {
			return cb.equal(root.get("mobile"), wxUser.getMobile());
		});
		if (list.isEmpty()) {
			throw new RuntimeException("没有登记的手机号码");
		} else {
			if (list.size() == 1) {
				wxUserRepository.save(wxUser); // 获取到的微信用户信息保存到数据库，意义也不大，看看再说吧
				user = list.get(0);
				user.setWxUserId(userId);
				userRepository.save(user); //将用户信息与微信的UserID进行关联
			} else {
				throw new RuntimeException("要绑定的手机号码在系统中存在多个用户对应");
			}
		}
		return user;
	}

}
